package com.woniuxy.dr_mall.shiro;

import com.woniuxy.dr_mall.entity.DrPerm;
import com.woniuxy.dr_mall.entity.DrUser;
import com.woniuxy.dr_mall.mapper.DrUserMapper;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.web.session.HttpServletSession;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * @author 张哲轩
 * @version 1.0.0
 * @ClassName DbRealm.java
 * @createTime 2021年07月29日 15:29:00
 */
public class DbRealm extends AuthorizingRealm {

    @Autowired
    private DrUserMapper userMapper;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        Object o = principals.getPrimaryPrincipal();
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        if (o instanceof DrUser) {
            DrUser user = (DrUser) o;
            //TODO
            List<DrPerm> pl = null;
            for (DrPerm p : pl) {
                info.addStringPermission(p.getCode());
            }
        }
        return  info;
    }


    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        UsernamePasswordToken t = (UsernamePasswordToken) token;
        DrUser user = userMapper.getByAccount(t.getUsername());
        if (user == null) {
            throw new UnknownAccountException("账号：" + t.getUsername() + "不存在");
        }
        SecurityUtils.getSubject().getSession().setAttribute("user", user);
//        ByteSource salt = ByteSource.Util.bytes("123");
        return new SimpleAuthenticationInfo(user, user.getPassword(), getName());
    }

    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof UsernamePasswordToken;
    }
}
